﻿var $edittr = null;
var ServiceId = GetQueryString("Id");
var dataSourceId = GetQueryString("dataSourceId");
$(function () {
    $("#DataServiceId").val(ServiceId);
    getServiceDetails();
    GetCodeDataTypeSelectList();
    if (dataSourceId != "") {
        $(".sub_Title").html("编辑数据源-DataBase");
        $("#hidden_input").append("<input type=\"hidden\" name=\"DataSourceId\" id=\"DataSourceId\" value=\"" + dataSourceId + "\"/>");
        getDataSourceDetails();
        $("#SourceName").attr("disabled", "disabled");
        $("#SourceValue").attr("disabled", "disabled");
        $("#SourceType-2").attr("disabled", "disabled");
        $("#SourceType-1").attr("disabled", "disabled");
    }
    $("#add-parameter-form").validate({
        submitHandler: function () {
            var jsonobj = {};
            jsonobj.name = $("#add-parameter-Name").val();
            jsonobj.type = $("#add-parameter-DataTypeSelect").val();
            jsonobj.description = $("#add-parameter-Description").val().replace(",", "，");
            jsonobj.defaultValue = $("#add-parameter-DefaultValue").val().replace(",", "，");
            jsonobj.id = "";
            var tr = AssembleParameterData(jsonobj);
            $("#table-details-parameter").append(tr);
            $('#add-parameter-modal').modal('hide');
            ShowGritter("添加成功");
            console.log(JSON.stringify(tr));
        }
    });
    $("#update-parameter-form").validate({
        submitHandler: function () {
            var jsonobj = {};
            jsonobj.name = $("#update-parameter-Name").val();
            jsonobj.type = $("#update-parameter-DataTypeSelect").val();
            jsonobj.description = $("#update-parameter-Description").val().replace(",", "，");
            jsonobj.defaultValue = $("#update-parameter-DefaultValue").val().replace(",", "，");
            jsonobj.id = "";
            if ($edittr != null) {
                $(AssembleParameterData(jsonobj)).replaceAll($edittr);
            }

            $('#update-parameter-modal').modal('hide');
            ShowGritter("编辑成功");
            console.log(JSON.stringify(jsonobj));
        }
    });
    $("#add-column-form").validate({
        submitHandler: function () {
            var jsonobj = {};
            jsonobj.name = $("#add-column-Name").val();
            jsonobj.type = $("#add-column-DataTypeSelect").val();
            jsonobj.description = $("#add-column-Description").val().replace(",", "，");
            jsonobj.id = "";
            var tr = AssembleColumnData(jsonobj);
            $("#table-details-column").append(tr);
            $('#add-column-modal').modal('hide');
            ShowGritter("添加成功");
            console.log(JSON.stringify(jsonobj));
        }
    });
    $("#update-column-form").validate({
        submitHandler: function () {
            var jsonobj = {};
            jsonobj.name = $("#update-column-Name").val();
            jsonobj.type = $("#update-column-DataTypeSelect").val();
            jsonobj.description = $("#update-column-Description").val().replace(",", "，");
            jsonobj.id = "";
            if ($edittr != null) {
                $(AssembleColumnData(jsonobj)).replaceAll($edittr);
            }
            $('#update-column-modal').modal('hide');
            ShowGritter("编辑成功");
            console.log(JSON.stringify(jsonobj));
        }
    });
    $("#AddDataSource").validate({
        submitHandler: function () {
            var columnlist = $("#table-details-column tbody tr");
            var parameterlist = $("#table-details-parameter tbody tr");
            if (columnlist.length > 0 && parameterlist.length > 0) {
                var str = "";
                var parstr = "";
                for (var i = 0; i < columnlist.length; i++) {
                    var tempjson = JSON.parse($(columnlist[i]).attr("data"));
                    str += (tempjson.name + ",");
                    str += (tempjson.type + ",");
                    str += (tempjson.description);
                    if (i != (columnlist.length - 1)) {
                        str += ",";
                    }
                }
                for (var j = 0; j < parameterlist.length; j++) {
                    var tempjson1 = JSON.parse($(parameterlist[j]).attr("data"));
                    parstr += (tempjson1.name + ",");
                    parstr += (tempjson1.type + ",");
                    parstr += (tempjson1.defaultValue + ",");
                    parstr += (tempjson1.description);
                    if (j != (parameterlist.length - 1)) {
                        parstr += ",";
                    }
                }
                $("#ColumnSettings").val(str);
                $("#ParameterSettings").val(parstr);
                //修改
                var url = "DataSourceDetails-DatabaseSQL.html?Id=" + ServiceId;
                if (dataSourceId != "") {
                    $.ajax({
                        url: apiUrl,
                        type: "Post",
                        dataType: "json",
                        data: {
                            "sys:sno": "ETL",
                            "sys:act": "UpdateDataSourceParameters",
                            "ServiceId": ServiceId,
                            "SourceId": dataSourceId,
                            "ParameterSettings": parstr
                        },
                        success: function (data) {
                            ShowGritter("修改输入参数成功!");
                            if (data.IsSccuess) {
                                $.ajax({
                                    url: apiUrl,
                                    type: "Post",
                                    dataType: "json",
                                    data: {
                                        "sys:sno": "ETL",
                                        "sys:act": "UpdateDataSourceColumns",
                                        "ServiceId": ServiceId,
                                        "SourceId": dataSourceId,
                                        "ColumnSettings": str
                                    },
                                    success: function (result) {
                                        if (result.IsSccuess) {

                                            ShowGritter("修改返回参数成功!", 2, url);

                                        } else {
                                            if (IsLogined(data.ErrorCode)) {
                                                alert("修改失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                                                window.location.href = loginUrl;
                                            }
                                        }
                                    },
                                    beforeSend: function () {
                                        ShowGritter("正在提交返回参数的修改");

                                    }
                                });

                            } else {
                                if (IsLogined(data.ErrorCode)) {
                                    alert("修改失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                                }
                            }
                        },
                        beforeSend: function () {
                            ShowGritter("正在提交输入参数的修改");
                        }
                    });

                } else { //新增
                    $.ajax({
                        url: apiUrl,
                        type: "Post",
                        dataType: "json",
                        data: $("#AddDataSource").serialize(),
                        success: function (data) {
                            if (data.IsSccuess) {
                                ShowGritter("保存成功!", 2, url);
                            } else {
                                if (IsLogined(data.ErrorCode)) {
                                    alert("新增失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                                }
                            }
                        },
                        beforeSend: function () {
                            ShowGritter("正在提交");
                        }
                    });
                }
            } else {
                ShowGritter("参数列表为空或返回数据参数列表为空，不允许提交");
            }

        }
    });
});
//组合参数数据  编辑时需调用此方法处理返回的数据
//传入的参数类型为对象数组
var AppadParameterData = function (data) {
    //var list = new Array();
    var trlist = "";
    for (var i = 0; i < data.length; i++) {
        var $this = data[i];
        //list.push({ name: $this.Name, id: $this.Id, type: $this.Type, description: $this.Description });
        trlist += AssembleParameterData({ name: $this.Name, id: $this.Id, type: $this.Type, description: $this.Description, defaultValue: $this.DefaultValue });
    }
    $("#table-details-parameter").append(trlist);
}
//传入参数对象返回一行的表格数据
var AssembleParameterData = function (data) {
    var tr = "<tr data='" + JSON.stringify(data) + "'><td>";
    tr += (data.name + "</td>");
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td>" + data.defaultValue + "</td>");
    tr += ("<td>" + data.description + "</td>");//备注
    tr += ("<td>  <a href='javascript:void(0)' onclick=\"UpateParameterData(this)\"><i class='fa fa-pencil-square-o '></i>编辑</a>&nbsp;<a href='javascript:void(0)' onclick=\"DeleteData(this)\"><i class='fa  fa-times-circle'></i>删除</a></td></tr>");
    return tr;
}


//组合列数据
//传入的参数类型为对象数组
var AppadColumnData = function (data) {
    //var list = new Array();
    var trlist = "";
    for (var i = 0; i < data.length; i++) {
        var $this = data[i];
        //list.push({ name: $this.Name, id: $this.Id, type: $this.Type, description: $this.Description });
        trlist += AssembleColumnData({ name: $this.Name, id: $this.Id, type: $this.Type, description: $this.Description });
    }
    $("#table-details-column").append(trlist);
}
//传入列对象返回一行的表格数据
var AssembleColumnData = function (data) {
    var tr = "<tr data='" + JSON.stringify(data) + "'><td>";
    tr += (data.name + "</td>");
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td>" + data.description + "</td>");//备注
    tr += ("<td>  <a href='javascript:void(0)' onclick=\"UpateColumnData(this)\"><i class='fa fa-pencil-square-o '></i>编辑</a>&nbsp;<a href='javascript:void(0)' onclick=\"DeleteData(this)\"><i class='fa  fa-times-circle'></i>删除</a></td></tr>");
    return tr;
}

//获取可用代码的select列表
var GetCodeDataTypeSelectList = function () {
    var list = GetCodeDataType();
    var str = "";

    for (var i = 0; i < list.length; i++) {
        str += ("<option value=\"" + list[i] + "\">" + list[i] + "</option>");
    }
    $("#add-parameter-DataTypeSelect").append(str);
    $("#update-parameter-DataTypeSelect").append(str);
    $("#add-column-DataTypeSelect").append(str);
    $("#update-column-DataTypeSelect").append(str);
}
//删除当前行数据
var DeleteData = function (obj) {
    if (confirm("是否删除？")) {
        $(obj).parent().parent().remove();
    }
}
//获取服务的详细信息
var getServiceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "SQL",
            "sys:act": "GetDataService",
            "ServiceId": ServiceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                $("#ServiceName").val(data.Data.Name);
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
//获取服务信息
var getDataSourceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "ETL",
            "sys:act": "GetDataSource",
            "DataServiceId": ServiceId,
            "DataSourceId": dataSourceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                var str = "";
                $("#SourceName").val(data.Data.Name);//名称
                $("#SourceValue").val(data.Data.Value);
                if (data.Data.Type == 1) {
                    $("#SourceType-1").attr("checked", "checked");
                    $("#SourceType-2").removeAttr("checked");
                } else {
                    $("#SourceType-2").attr("checked", "checked");
                    $("#SourceType-1").removeAttr("checked");
                }
                AppadColumnData(data.Data.Columns);//组装数据并并填充表格
                AppadParameterData(data.Data.Parameters);//组装数据并并填充表格
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
//编辑返回参数按钮触发的操作
var UpateColumnData = function (obj) {
    var tr = $(obj).parent().parent();
    $edittr = tr;
    var json = tr.attr("data");
    var jsonobj = JSON.parse(json);
    $("#update-column-Name").val(jsonobj.name);
    $("#update-column-DataTypeSelect").val(jsonobj.type);
    $("#update-column-Description").val(jsonobj.description);
    $('#update-column-modal').modal({
        show: true
    });
}
//新增返回参数按钮触发的操作
var AddColumn = function () {
    document.getElementById('add-column-form').reset();
    $('#add-column-modal').modal({
        show: true
    });
}
//编辑传入参数按钮触发的操作
var UpateParameterData = function (obj) {
    var tr = $(obj).parent().parent();
    $edittr = tr;
    var json = tr.attr("data");
    var jsonobj = JSON.parse(json);
    $("#update-parameter-Name").val(jsonobj.name);
    $("#update-parameter-DataTypeSelect").val(jsonobj.type);
    $("#update-parameter-Description").val(jsonobj.description);
    $("#update-parameter-DefaultValue").val(jsonobj.defaultValue);
    $('#update-parameter-modal').modal({
        show: true
    });
}
//新增传入参数按钮触发的操作
var AddParameter = function () {
    document.getElementById('add-parameter-form').reset();
    $('#add-parameter-modal').modal({
        show: true
    });
}